<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分组" prop="group">
        <el-input
          v-model="queryParams.group"
          placeholder="请输入分组"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="代码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入代码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in dict.type.ext_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['api:model:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleLoad"
        >刷新缓存</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="index" width="55" align="center" />
      <el-table-column label="代码" align="center" prop="code" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="主键" align="center" prop="pk_field" />
      <el-table-column label="唯一字段" align="center" prop="unique_field" />
      <el-table-column label="分组" align="center" prop="group" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ext_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="内置模型" align="center" prop="is_default">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.is_default"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.is_default == 'N'">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['api:model:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['api:model:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />

    <!-- 添加或修改数据模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-tabs v-model="tab">
        <el-tab-pane label="模型信息" name="base">
        <el-form-item label="代码" prop="code">
          <el-input v-model="form.code" placeholder="请输入数据库表名" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="主键字段" prop="pk_field">
          <el-input v-model="form.pk_field" placeholder="请输入主键字段" />
        </el-form-item>
        <el-form-item label="唯一字段" prop="unique_field">
          <el-input v-model="form.unique_field" placeholder="唯一字段，多个用,隔开" />
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="form.group" placeholder="请输入分组" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.ext_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注详细" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注详细" />
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="权限控制" name="scope">
        <el-form-item label="组织权限" prop="org_scope">
          <el-input type="textarea" rows="3" v-model="form.org_scope" placeholder="dept_id in (${_orgId})" />
        </el-form-item>
        <el-form-item label="用户权限" prop="user_scope">
          <el-input type="textarea" rows="3" v-model="form.user_scope" placeholder="user_id = #{_userId}" />
        </el-form-item>
        <el-form-item :label="role.name" v-for="(role,i) in accessForm" :key="i">
          <el-checkbox-group v-model="role.mode">
            <el-checkbox v-for="(a,i) in accessOptions" :key="i" :label="i">{{a}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="导入导出" name="excels">
        <el-form-item label="字段配置" prop="excels">
          <el-input type="textarea" rows="20" v-model="form.excels" placeholder="dept_id = ${deptId}" />
        </el-form-item>
        </el-tab-pane>
      </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiGet, apiPost, apiPatch, apiDelete, loadCache } from "@/api/openapi";

export default {
  name: "ApiModel",
  dicts: ['ext_status', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据模型表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      tab: 'base',
      // 查询参数
      queryParams: {
        group: null,
        code: null,
        name: null,
        status: null,
      },
      pager: {
        page: 1,
        limit: 10,
        order: "id desc",
      },
      // 表单参数
      form: {},
      accessForm:[],
      roleOptions:[],
      accessOptions:['读', '写'],
      // 表单校验
      rules: {
        code: [
          { required: true, message: "代码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        pk_field: [
          { required: true, message: "主键不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.loadRoles();
  },
  methods: {
    /** 查询数据模型列表 */
    getList() {
      this.loading = true;
      let params = {};
      params['api_model'] = this.queryParams;
      params['@pager'] = this.pager;
      apiGet(params).then(response => {
        this.modelList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    loadRoles() {
      let params = {};
      params['sys_role'] = {del_flag:0};
      params['@pager'] = {page:1, limit:1000};
      apiGet(params).then(response => {
        this.roleOptions = response.data.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        group: null,
        code: null,
        name: null,
        pk_field: 'id',
        unique_field: null,
        org_scope: null,
        user_scope: null,
        status: '1',
        remark: null,
        excels: null
      };
      this.resetForm("form");
      this.tab = 'base';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据模型";
      
      let roles = [];
      for(var i=0;i<this.roleOptions.length;i++){
        roles.push({name:this.roleOptions[i]['role_name'], id:this.roleOptions[i]['role_id'], mode:[]});
      }
      this.accessForm = roles;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['api_model'] = { id:id};
        data['api_access'] = { model_id:id, '@pager':{page:1, limit:1000}};
        apiGet(data).then(response => {
        this.form = response.data['api_model'];
        this.open = true;
        this.title = "修改数据模型";

        
        let roles = [];
        for(var i=0;i<this.roleOptions.length;i++){
          let role = {name:this.roleOptions[i]['role_name'], id:this.roleOptions[i]['role_id'], mode:[]};
          //回显
          if(response.data['api_access'] && response.data['api_access'].length > 0){
            for(var j=0;j<response.data['api_access'].length;j++){
              if(response.data['api_access'][j]['role_id'] == this.roleOptions[i]['role_id']){
                if(response.data['api_access'][j]['read'] == 'Y'){
                  role.mode.push(0);
                }
                if(response.data['api_access'][j]['write'] == 'Y'){
                  role.mode.push(1);
                }
              }
            }
          }
          roles.push(role);
        }
        this.accessForm = roles;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
            let data = {};
            data['api_model'] = this.form;
            data['@tags'] = ['api_model'];

            let accessList = [];
            let modelId = this.form.id ? this.form.id : '@api_model.id';
            for(var i=0;i<this.accessForm.length;i++){
              if(this.accessForm[i].mode.length == 0){
                continue;
              }
              var access = {model_id:modelId, role_id: this.accessForm[i]['id'], read:'N', write:'N'};
              if(this.accessForm[i].mode.indexOf(0) != -1){
                access['read'] = 'Y';
              }
              if(this.accessForm[i].mode.indexOf(1) != -1){
                access['write'] = 'Y';
              }
              accessList.push(access);
              console.log(access)
            }
            if(accessList.length > 0){
              data['api_access'] = accessList;
              data['@tags'].push('api_access');
            }

          if (this.form.id != null) {
            apiPatch(data).then(response => {
              this.loadModel();
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiPost(data).then(response => {
              this.loadModel();
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;    
      this.$modal.confirm('是否确认删除数据模型'+row.name+'？').then(function() {
        let data = {};
        data['api_model'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['api_model'];
        return apiDelete(data);
      }).then(() => {
        this.loadModel();
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    loadModel() {
      loadCache('model').then(() => {
        console.log('加载缓存成功')
      }).catch(() => {});
    },
    /** 加载缓存按钮操作 */
    handleLoad(row) {
      loadCache('model').then(() => {
        this.$modal.msgSuccess("操作成功");
      }).catch(() => {});
    },
    /** 权限按钮操作 */
    handleRole() {
      this.download('api/model/export', {
        ...this.queryParams
      }, `model_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
